<?php


namespace BoojasrFramework\Service;


use BoojasrFramework\Kernel;
use Twig\Environment;
use Twig\Extension\ExtensionInterface;
use Twig\Loader\FilesystemLoader;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;

class TwigService
{
    private $twig;

    private $loader;

    public function __construct()
    {
        $config = Kernel::getConfig();
        $this->loader = new FilesystemLoader();
        $viewConfig = $config["view"]??[];
        foreach ($viewConfig as $namespace=>$item){
            $viewPaths = [];
            if( isset($item["view_paths"])){
                $viewPaths = $item["view_paths"];
            }
            if (empty($viewPaths)) continue;
            foreach ($viewPaths as $viewPath){
                $this->loader->addPath($viewPath,$namespace);
            }
        }
        $options = [];
        if(isset($viewConfig["options"])){
            $options = $viewConfig["options"];
        }
        $this->twig = new Environment($this->loader, $options);
    }

    public function addFilter(TwigFilter $filter){
        $this->twig->addFilter($filter);
    }

    public function addExtension(ExtensionInterface $extension){
        $this->twig->addExtension($extension);
    }

    public function addFunction(TwigFunction $function){
        $this->twig->addFunction($function);
    }

    public function addGlobal(string $name, $value){
        $this->twig->addGlobal( $name, $value);
    }

    public function addNodeVisitor(NodeVisitorInterface $visitor){
        $this->twig->addNodeVisitor($visitor);
    }

    /**
     * @return Environment
     */
    public function getTwig(){
        return $this->twig;
    }



}
